Popular Searches
Popular Course Categories
Popular Courses

Working with Embedded Tomcat Servers

Working with Embedded Tomcat Servers

Spring Boot Application Development

Working with Embedded Tomcat Servers

Course: Advanced Java Training

Topic: Working with Embedded Tomcat Servers in Spring Boot

Course Link: Advanced Java Training Course

Demo Link: Register for a Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction to Embedded Tomcat

Apache Tomcat is an open-source web server and servlet container used to run Java web applications. It implements Jakarta Servlet specifications and provides the runtime environment required by applications that use servlet-based technologies such as Spring MVC.

An embedded Tomcat server runs inside the application process instead of requiring developers to install and configure a separate Tomcat server before running the application. Spring Boot can automatically configure an embedded server when the appropriate web dependency is included.

This approach is especially useful for developing REST APIs, Spring MVC applications, microservices, and independently deployable Java services.

Why Is Embedded Tomcat Useful?

  • Developers can run a web application directly from an IDE or command line.
  • The application can be packaged as an executable JAR.
  • A separate Tomcat installation is generally unnecessary for a standard embedded deployment.
  • Server configuration can be maintained in application properties or YAML.
  • It simplifies local development, automated testing, and container-based deployment.
  • It supports independently deployable applications and microservices.

2. What Is Apache Tomcat?

Apache Tomcat is a Java-based web server and servlet container. It receives HTTP requests, manages servlet execution, and sends HTTP responses back to clients.

In a Spring MVC application, Tomcat receives incoming HTTP requests and provides the servlet environment in which Spring's DispatcherServlet processes those requests.

Important Responsibilities of Tomcat

  • Accepting HTTP requests through configured connectors.
  • Managing servlet lifecycle and request processing.
  • Providing the servlet container environment for Spring MVC.
  • Handling HTTP connections and response delivery.
  • Supporting configured ports, connection settings, and server behavior.

3. Traditional Tomcat Deployment vs. Embedded Tomcat

Feature Traditional External Tomcat Embedded Tomcat
Server installation Usually requires a separately installed and managed Tomcat server. Tomcat libraries are included in the application runtime dependencies.
Deployment package Often uses a WAR deployed to an external server. Commonly uses an executable JAR containing the application and required runtime libraries.
Startup Start the server and deploy the application. Start the application process directly.
Configuration May involve external server configuration files and deployment settings. Can be configured through Spring Boot properties, YAML, and programmatic customizers.
Port management Often configured at the external server level. Can be configured through application settings such as server.port.
Deployment model Several applications may share a server installation. Each application can run as an independently managed process.
Common use cases Existing enterprise infrastructure and centralized server administration. Spring Boot services, APIs, and independently deployable applications.

Embedded Tomcat does not mean that Tomcat has disappeared. The server is still present; it is packaged as part of the application's runtime dependencies and started by Spring Boot.

4. How Embedded Tomcat Works in Spring Boot

When a Spring Boot web application starts, Spring Boot creates and configures an embedded servlet web server. The server begins listening on the configured port and accepts incoming HTTP requests.

  1. The developer starts the Spring Boot application.
  2. The Java main method calls SpringApplication.run().
  3. Spring Boot creates the application context.
  4. Web-related dependencies trigger servlet web application auto-configuration.
  5. Spring Boot configures the embedded Tomcat server and the servlet environment.
  6. The server starts listening on its configured port.
  7. Incoming requests reach the servlet container and are processed by Spring MVC when applicable.
  8. The application sends the resulting HTTP response to the client.

Request Processing Flow

Client / Browser
      |
      | HTTP Request
      v
Embedded Tomcat
      |
      v
Spring DispatcherServlet
      |
      v
Controller
      |
      v
Service Layer (if required)
      |
      v
Response / View
      |
      v
Embedded Tomcat
      |
      | HTTP Response
      v
Client / Browser

This is a simplified flow for a typical Spring MVC request. Applications may include additional components such as filters, interceptors, exception handlers, repositories, and security filters.

5. Creating a Spring Boot Project with Embedded Tomcat

Spring Boot commonly uses embedded Tomcat when a project includes the Spring Web starter for servlet-based web applications. Spring Boot manages the server configuration and starts it when the application launches.

Step 1: Generate the Project

  1. Open Spring Initializr.
  2. Select Maven as the project type.
  3. Select Java as the programming language.
  4. Choose a Spring Boot version compatible with your installed JDK.
  5. Enter the group as com.example and artifact as tomcat-demo.
  6. Select JAR packaging.
  7. Add the Spring Web dependency.
  8. Generate and download the project ZIP file.

Step 2: Understand the Maven Dependency

The generated pom.xml typically contains a Spring Web starter dependency similar to this:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

For a standard Spring MVC application, Spring Boot's dependency management brings in the embedded Tomcat starter unless it has been excluded or replaced. The exact dependency details depend on the Spring Boot version and selected build configuration.

Step 3: Examine the Main Application Class

package com.example.tomcatdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TomcatDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(TomcatDemoApplication.class, args);
    }
}

When the application starts, Spring Boot initializes the application context and configures the embedded servlet server because the required web dependencies are present.

6. Creating a Controller to Test Embedded Tomcat

A controller allows you to verify that the embedded server is receiving requests and returning responses.

Example: WelcomeController.java

package com.example.tomcatdemo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WelcomeController {

    @GetMapping("/")
    public String welcome() {
        return "Welcome to Spring Boot Embedded Tomcat!";
    }

    @GetMapping("/status")
    public String status() {
        return "Application is running successfully.";
    }
}

Explanation

  • @RestController identifies the class as a REST controller.
  • @GetMapping("/") maps HTTP GET requests to the root path.
  • @GetMapping("/status") creates another endpoint for checking application availability.
  • The returned strings are written to the HTTP response body.

7. Running the Application

Open the generated project in an IDE and allow Maven to download the required dependencies. You can run the main application class directly or start the application from the command line.

Windows

mvnw.cmd spring-boot:run

macOS or Linux

./mvnw spring-boot:run

If Maven is installed globally, you can also use mvn spring-boot:run.

After startup, check the console for messages indicating that the embedded server has started and note the port being used.

Test the Endpoints

Open these URLs in a browser or API testing tool, assuming the application uses the default port:

http://localhost:8080/
http://localhost:8080/status

Expected response from the root endpoint:

Welcome to Spring Boot Embedded Tomcat!

Expected response from the status endpoint:

Application is running successfully.

8. Configuring the Embedded Tomcat Port

Spring Boot commonly uses port 8080 by default for a standalone servlet web application. You can change the port using the server.port property.

Using application.properties

spring.application.name=tomcat-demo
server.port=9090

Using application.yml

spring:
  application:
    name: tomcat-demo

server:
  port: 9090

Restart the application and test the endpoint at http://localhost:9090/.

Using a Command-Line Argument

java -jar target/tomcat-demo.jar --server.port=9090

The JAR filename depends on your project's artifact and version settings. A command-line property can override the packaged default configuration.

Using a Random Port

server.port=0

Setting the port to 0 allows the operating system to choose an available port. This can be useful for automated tests or applications that do not require a fixed local port. Check the startup logs or the application's web-server context to discover the assigned port.

9. Customizing Embedded Tomcat

Many common server settings can be configured through Spring Boot properties. When a required setting is not available through a property, a server factory customizer can be used for supported customization.

Example: Configure Tomcat Access Logging

# application.properties
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b

This example enables Tomcat access logging and specifies a log pattern. Review the logging location and access permissions for your deployment environment. The exact location depends on the Tomcat base directory and application configuration.

Example: Customize the Tomcat Server Factory

The following example illustrates how to register a customizer for the embedded Tomcat server. The precise Tomcat factory package can vary between Spring Boot major versions, so use the API appropriate for the version selected in your project.

package com.example.tomcatdemo.config;

import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;

// Use the Tomcat servlet web-server factory class
// provided by your Spring Boot version.

@Component
public class TomcatServerCustomizer {

    // Define a WebServerFactoryCustomizer bean
    // with the appropriate Tomcat factory type
    // when server-specific customization is required.
}

For ordinary configuration such as changing the port, enabling compression, or configuring SSL, prefer documented Spring Boot properties over custom Java configuration. Customizers are best reserved for settings that cannot be expressed through the supported properties.

10. Enabling HTTP Response Compression

HTTP response compression can reduce the amount of data transferred to clients, especially for suitable text-based responses such as HTML, CSS, and JSON.

# application.properties
server.compression.enabled=true
server.compression.min-response-size=2048

The minimum response size controls when compression becomes eligible. Actual compression depends on the response type, client request headers, and server configuration.

11. Configuring HTTPS for Embedded Tomcat

HTTPS encrypts communication between the client and server. Spring Boot supports configuring TLS for an embedded server through SSL-related properties and suitable certificate material.

A simplified example using a Java KeyStore is shown below. The file and passwords are placeholders and must be replaced with valid, securely managed values.

# application.properties
server.port=8443
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=${KEYSTORE_PASSWORD}
server.ssl.key-store-type=PKCS12
server.ssl.key-alias=tomcat

Place the certificate store at the configured location or use an appropriate external path. Supply the password securely through the environment or a secret manager. Never commit real production credentials or private keys to a public repository.

For production systems, use certificates issued and managed according to the organization's security requirements. If a reverse proxy or load balancer terminates TLS, configure forwarded headers carefully and trust only known proxies.

12. Embedded Tomcat and Executable JAR Packaging

One major advantage of embedded Tomcat is the ability to package a Spring Boot application as an executable JAR. The package includes the application code and its required runtime libraries, including the embedded server dependencies.

Build the JAR

# Windows
mvnw.cmd clean package

# macOS or Linux
./mvnw clean package

After a successful build, the executable JAR is typically generated under the Maven target directory.

Run the JAR

java -jar target/tomcat-demo.jar

Use the actual JAR filename generated by your build. If the project is configured correctly, the application starts and launches the embedded server without requiring a separate Tomcat installation.

Benefits of Executable JAR Deployment

  • Provides a convenient deployment artifact.
  • Includes the libraries needed to run the application.
  • Simplifies local execution and many automated deployment workflows.
  • Works well with containerized deployments.
  • Allows the application and its runtime dependencies to be versioned together.

13. Embedded Tomcat vs. External Tomcat Deployment

Aspect Embedded Tomcat External Tomcat
Deployment artifact Commonly an executable JAR Commonly a WAR file
Server lifecycle Starts and stops with the application process Managed separately from the deployed application
Configuration Often managed with Spring Boot settings May involve both server-level and application-level configuration
Infrastructure Suitable for independently deployed services Useful when an organization already operates a shared Tomcat platform
Maintenance Server dependencies are upgraded with application dependency management Server installation and deployed application lifecycle may be managed separately
Typical use Spring Boot APIs and microservices Existing application-server environments and WAR-based deployments

Neither approach is universally best. Select the deployment model based on infrastructure, operational policies, compatibility, security requirements, and team experience.

14. Common Problems and Troubleshooting

Problem Possible Cause Solution
Port already in use Another process is using the configured port. Stop the conflicting process or configure a different port using server.port.
Tomcat does not start Dependency conflict, invalid configuration, or server initialization error. Read the startup logs and inspect the first meaningful exception.
Application returns 404 Incorrect request URL, missing controller mapping, or component scanning issue. Verify the endpoint path, controller annotations, and package structure.
Dependencies fail to download Network, repository, proxy, or build configuration issue. Check network connectivity, repository configuration, and Maven or Gradle logs.
Java compatibility error JDK does not match the selected Spring Boot requirements. Install a supported JDK and align the IDE and build tool with it.
JAR does not run Incorrect filename, incomplete build, or incompatible Java runtime. Build the project again and verify the JAR path and runtime version.
HTTPS setup fails Invalid certificate store, alias, password, or certificate configuration. Verify certificate details and securely supplied configuration values.
Unexpected server settings Environment variables or command-line arguments override file settings. Inspect active profiles and higher-priority configuration sources.

15. Best Practices for Embedded Tomcat

  • Use a Spring Boot version compatible with the application's Java version and dependencies.
  • Keep server settings in external configuration wherever appropriate.
  • Use environment-specific configuration for development, testing, and production.
  • Do not expose management or diagnostic endpoints publicly without suitable access controls.
  • Use HTTPS and appropriate certificate management for sensitive production traffic.
  • Monitor application startup, server errors, response times, and resource usage.
  • Keep dependencies updated and review relevant security advisories.
  • Use graceful shutdown and suitable health checks for managed deployments.
  • Test server configuration and endpoints before releasing the application.
  • Use a reverse proxy or load balancer when required by the deployment architecture.

16. Practical Exercise

Objective: Create a Spring Boot REST application that runs on embedded Tomcat and exposes two endpoints.

  1. Generate a Maven project with Java and the Spring Web dependency.
  2. Import the project into your IDE.
  3. Create a main application class with @SpringBootApplication.
  4. Create a controller with a root endpoint and a status endpoint.
  5. Set server.port=9090 in application.properties.
  6. Run the application and confirm that the embedded server starts.
  7. Test http://localhost:9090/ and http://localhost:9090/status.
  8. Package the application using the Maven wrapper.
  9. Run the generated JAR using java -jar.
  10. Change the configured port and verify that the application uses the new setting.

Expected Outcome

You should have a runnable Spring Boot application that starts its embedded Tomcat server, handles HTTP requests, and can be packaged as an executable JAR.

17. Interview Questions and Answers

Q1. What is embedded Tomcat?

Answer: Embedded Tomcat is a servlet container included as an application runtime dependency, allowing a Spring Boot web application to start its own server process.

Q2. Which dependency commonly provides embedded Tomcat in Spring Boot?

Answer: For the traditional servlet-based Spring MVC stack, spring-boot-starter-web commonly brings in spring-boot-starter-tomcat, unless the dependency is excluded or replaced.

Q3. What is the default HTTP port commonly used by Spring Boot?

Answer: Port 8080 is the common default for a standalone web application unless the configuration changes it.

Q4. How can you change the embedded Tomcat port?

Answer: Set server.port in a Properties or YAML configuration file, or provide an appropriate command-line or environment override.

Q5. Does embedded Tomcat require a separate Tomcat installation?

Answer: A standard embedded deployment generally does not require a separately installed Tomcat server because the necessary server libraries are included in the application runtime dependencies.

Q6. Can a Spring Boot application be packaged as a JAR?

Answer: Yes. A Spring Boot application can commonly be packaged as an executable JAR and started using the Java command.

Q7. What happens when the configured port is already in use?

Answer: The server normally fails to bind to that port. Stop the conflicting process or configure an available port.

Q8. How can embedded Tomcat access logging be enabled?

Answer: Configure the supported Tomcat access-log properties, such as server.tomcat.accesslog.enabled=true, and review the output location and log pattern.

Q9. Can Spring Boot use a server other than Tomcat?

Answer: Yes. Depending on the web stack and Spring Boot version, alternative servers such as Jetty can be used by adjusting the relevant dependencies.

Q10. What is the difference between embedded and external Tomcat?

Answer: Embedded Tomcat is started with the application process, whereas external Tomcat is installed and managed separately, with applications deployed to that server.

18. Quick Revision Checklist

  • Understand Tomcat's role as a servlet container.
  • Know how Spring Boot starts an embedded web server.
  • Understand the role of the Spring Web starter dependency.
  • Know how to configure server.port.
  • Be able to create and test a basic REST controller.
  • Understand executable JAR packaging and application startup.
  • Know how to investigate port conflicts and startup errors.
  • Understand the difference between embedded and external server deployment.
  • Follow security and monitoring best practices for production applications.

19. Conclusion

Embedded Tomcat makes Spring Boot web development simpler by allowing applications to start their own servlet server without depending on a separate Tomcat installation. With the Spring Web starter, a main application class, a controller, and suitable configuration, developers can quickly build and run REST APIs or Spring MVC applications.

Learning how to configure ports, customize server settings, package executable JARs, troubleshoot startup problems, and apply production security practices provides a strong foundation for developing and deploying Spring Boot applications.


Useful Learning Resources

Previous Next
whatsapp